package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.ReportService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private ReportService reportService;

    @Autowired
    private JedisPool jedisPool;



    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        List<String> list = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,-12);

        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
            String format = sdf.format(calendar.getTime());
            list.add(format);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("months",list);

        List<Integer> countList = reportService.countByMonth(list);
        map.put("memberCount",countList);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    @RequestMapping("/getMemberReportByDate")
    public Result getMemberReportByDate(@RequestBody String[] dates) {
        List<Date> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        List<String> result = new ArrayList<>();
        if (dates != null) {
            try {
                String minDate = dates[0];
                String maxDate = dates[1];
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

                Calendar min = Calendar.getInstance();
                Calendar max = Calendar.getInstance();

                min.setTime(sdf.parse(minDate));
                min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

                max.setTime(sdf.parse(maxDate));
                max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

                Calendar curr = min;
                while (curr.before(max)) {
                    result.add(sdf.format(curr.getTime()));
                    curr.add(Calendar.MONTH, 1);
                }
                map.put("months", result);

                List<Integer> countList = reportService.countByDate(result);

                map.put("memberCount", countList);

                return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
        return null;
    }


//    getSetmealReport
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){

        List<Map<String,Object>> setmealCount = reportService.setmealCount();
        Map<String,Object> objectMap = new HashMap<>();
        objectMap.put("setmealCount",setmealCount);

        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> map : setmealCount) {
            String name = (String) map.get("name");
            setmealNames.add(name);
        }
        objectMap.put("setmealNames",setmealNames);

        return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,objectMap);
    }

    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        Map<String,Object> map = reportService.getBusinessReportData();
        return new Result(true,"获取数据成功",map);
    }

    //exportBusinessReport
    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,Object> map = reportService.exportBusinessReport();
        String reportDate = (String) map.get("reportDate");
        Integer todayNewMember = (Integer) map.get("todayNewMember");
        Integer totalMember = (Integer) map.get("totalMember");
        Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
        Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
        Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
        Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
        Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
        Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
        Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
        Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
        List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");

        String realpath = request.getSession().getServletContext().getRealPath("template") + File.separator+"report_template.xlsx";

        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(new File(realpath)));
        //第一张表
        XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
        //获取第二行
        XSSFRow row = sheetAt.getRow(2);
        //日期
        row.getCell(5).setCellValue(reportDate);
        //获取第四行
        row = sheetAt.getRow(4);
        //新增会员数
        row.getCell(5).setCellValue(todayNewMember);
        //总会员
        row.getCell(7).setCellValue(totalMember);

        row = sheetAt.getRow(5);
        //本周新增会员数
        row.getCell(5).setCellValue(thisWeekNewMember);
        //本月新增会员数
        row.getCell(7).setCellValue(thisMonthNewMember);

        row = sheetAt.getRow(7);
        //今日预约数
        row.getCell(5).setCellValue(todayOrderNumber);
        //今日到诊数
        row.getCell(7).setCellValue(todayVisitsNumber);

        row = sheetAt.getRow(8);
        row.getCell(5).setCellValue(thisWeekOrderNumber);
        row.getCell(7).setCellValue(thisWeekVisitsNumber);

        row = sheetAt.getRow(9);
        row.getCell(5).setCellValue(thisMonthOrderNumber);
        row.getCell(7).setCellValue(thisMonthVisitsNumber);


        int rownum = 12;
        for (Map map1 : hotSetmeal) {
            String name = (String) map1.get("name");
            Long package_count = (Long) map1.get("package_count");
            BigDecimal proportion = (BigDecimal) map1.get("proportion");
            String remark = (String) map1.get("remark");
            row = sheetAt.getRow(rownum++);
            row.getCell(4).setCellValue(name);
            row.getCell(5).setCellValue(package_count);
            row.getCell(6).setCellValue(proportion.doubleValue());
            row.getCell(7).setCellValue(remark);
        }

        //通过输出流进行文件下载

        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        String filnema = new String("报表".getBytes(),"ISO-8859-1");
        response.setHeader("content-Disposition", "attachment;filename="+filnema+".xlsx");
        xssfWorkbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
        xssfWorkbook.close();
        return new Result(true,"数据到处成功");
    }

    /**
     * 会员数量占比(性别)
     * @return
     */
    @GetMapping("/getMemberSexReport")
    public Result getMemberSexReport(){

        List<Map<String,Object>> memberSexCount = reportService.getMemberSexCount();
        Map<String,Object> objectMap = new HashMap<>();
        objectMap.put("memberSexCount",memberSexCount);

        List<String> memberSexList = new ArrayList<>();
        for (Map<String, Object> map : memberSexCount) {
            String sex = (String) map.get("name");
            memberSexList.add(sex);
        }
        objectMap.put("memberSex",memberSexList);

        return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,objectMap);
    }

    /**
     * 会员数量占比(年龄)
     * @return
     */
    @GetMapping("/getMemberAgeReport")
    public Result getMemberAgeReport(){

        try {
            List<Map<String,Object>> memberSexCount = reportService.getMemberAgeCount();
            Map<String,Object> objectMap = new HashMap<>();
            objectMap.put("memberAgeCount",memberSexCount);

            List<String> memberSexList = new ArrayList<>();
            for (Map<String, Object> map : memberSexCount) {
                String age = (String) map.get("name");
                memberSexList.add(age);
            }
            objectMap.put("memberAge",memberSexList);

            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,objectMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }


}